import React, { useState, useRef } from 'react';
import { Form, Input, Button, Typography, Spin, message, Card, Row, Col, Select, InputNumber } from 'antd';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { Title, Text } = Typography;
const { TextArea } = Input;

export default function LittleRedBookCopywriting() {
  const [form] = Form.useForm();
  const [isGenerating, setIsGenerating] = useState<boolean>(false);
  const [generatedContent, setGeneratedContent] = useState<string>('');
  const [tourVisible, setTourVisible] = useState(false);

  // 使用HTML元素的ref引用方式
  const productNameRef = useRef<HTMLDivElement>(null);
  const targetAudienceRef = useRef<HTMLDivElement>(null);
  const featuresRef = useRef<HTMLDivElement>(null);
  const styleRef = useRef<HTMLDivElement>(null);
  const toneRef = useRef<HTMLDivElement>(null);
  const submitRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);

  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };

  // 生成小红书文案的模拟函数
  const generateContent = (productName: string, features: string, targetAudience: string, style: string, tone: string): string => {
    // 这里是模拟生成内容的逻辑，实际应用中应该调用AI模型
    let result = `💖 ${productName} | ${targetAudience}必看！\n\n`;
    result += `✨ 今天要给大家安利的是${productName}！`;
    if (features) {
      result += ` 它的主要特点包括：${features}。`;
    }
    result += `\n\n根据${style}风格和${tone}语气，我精心撰写了以下内容：\n\n`;

    // 模拟生成的段落
    result += "🌈 这是什么神仙好物！";
    if (style === '种草') {
      result += "我已经用了两周了，真的是相见恨晚！";
    } else if (style === '测评') {
      result += "经过一周的深度使用，我来给大家做个客观测评。";
    } else if (style === '教程') {
      result += "今天手把手教大家如何正确使用这款产品。";
    }
    result += `\n\n`;

    // 产品特点介绍
    if (features) {
      result += "🌟 使用感受分享：\n";
      const featureList = features.split('，');
      featureList.forEach((feature, index) => {
        result += `• ${feature}\n`;
      });
      result += "\n";
    }

    // 根据语气调整结尾
    if (tone === '活泼可爱') {
      result += "💌 总之，这绝对是提升生活幸福感的好物！姐妹们快冲鸭！🛍️\n\n";
    } else if (tone === '专业客观') {
      result += "📝 总体来说，这款产品在同价位中表现优异，值得一试。\n\n";
    } else if (tone === '温馨治愈') {
      result += "🌸 希望我的分享能给你带来一些温暖和灵感，我们下次再见啦～\n\n";
    }

    // 标签
    result += `#${productName.replace(/\s+/g, '')} #种草推荐 #好物分享 #${targetAudience.replace(/\s+/g, '')}\n\n`;
    result += "#小红书原创 #生活方式 #提升幸福感的小物\n\n";
    result += "✨ 喜欢的话记得点赞收藏关注我哦～下次分享更多好东西！✨";

    return result;
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      setIsGenerating(true);
      const { productName, features, targetAudience, style, tone } = values;

      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 1500));

      const content = generateContent(productName, features, targetAudience, style, tone);
      setGeneratedContent(content);
      message.success('小红书文案生成成功！');
    } catch (error) {
      message.error('生成失败，请稍后重试');
    } finally {
      setIsGenerating(false);
    }
  };

  // 复制生成的内容
  const handleCopy = () => {
    navigator.clipboard.writeText(generatedContent).then(() => {
      message.success('内容已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 下载生成的内容
  const handleDownload = () => {
    const blob = new Blob([generatedContent], { type: 'text/plain;charset=utf-8' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '小红书文案.txt';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    message.success('文件下载成功');
  };

  // 定义引导步骤
  const tourSteps = [
    {
      key: 'productName',
      title: '输入产品名称',
      description: '请输入您想要推广的产品名称',
    },
    {
      key: 'targetAudience',
      title: '输入目标受众',
      description: '请指定您的目标用户群体，如上班族、学生党等',
    },
    {
      key: 'features',
      title: '输入产品特点',
      description: '请输入产品的主要特点，多个特点用逗号分隔',
    },
    {
      key: 'style',
      title: '选择内容风格',
      description: '选择适合您产品的内容风格，如种草、测评等',
    },
    {
      key: 'tone',
      title: '选择写作语气',
      description: '选择您想要的文案语气，如活泼可爱、专业客观等',
    },
    {
      key: 'submit',
      title: '生成小红书文案',
      description: '点击按钮生成符合小红书平台风格的文案',
    },
    {
      key: 'result',
      title: '查看生成结果',
      description: '生成成功后，您可以在此处查看、复制或下载生成的文案',
    },
  ];

  // 组织ref引用
  const tourRefs = {
    productName: productNameRef,
    targetAudience: targetAudienceRef,
    features: featuresRef,
    style: styleRef,
    tone: toneRef,
    submit: submitRef,
    result: resultRef,
  };

  // 风格选项
  const styleOptions = [
    { label: '种草', value: '种草' },
    { label: '测评', value: '测评' },
    { label: '教程', value: '教程' },
    { label: '开箱', value: '开箱' },
    { label: '日常', value: '日常' },
  ];

  // 语气选项
  const toneOptions = [
    { label: '活泼可爱', value: '活泼可爱' },
    { label: '专业客观', value: '专业客观' },
    { label: '温馨治愈', value: '温馨治愈' },
    { label: '幽默风趣', value: '幽默风趣' },
  ];

  return (
    <>
      <div style={{ padding: '24px' }}>
        <div style={{ marginBottom: 24 }}>
          <Title level={2} style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
            小红书文案生成
            <TourGuideButton onClick={showTour} />
          </Title>
        </div>
        <Card style={{ marginBottom: '24px' }}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{
              style: '种草',
              tone: '活泼可爱',
            }}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <Form.Item
                  name="productName"
                  label="产品名称"
                  rules={[{ required: true, message: '请输入产品名称' }]}
                >
                  <div ref={productNameRef}>
                    <Input placeholder="请输入产品名称" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="targetAudience"
                  label="目标受众"
                  rules={[{ required: true, message: '请输入目标受众' }]}
                >
                  <div ref={targetAudienceRef}>
                    <Input placeholder="例如：上班族、学生党、宝妈等" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="features"
                  label="产品特点"
                >
                  <div ref={featuresRef}>
                    <Input placeholder="请输入产品特点，用逗号分隔" />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="style"
                  label="内容风格"
                  rules={[{ required: true, message: '请选择内容风格' }]}
                >
                  <div ref={styleRef}>
                    <Select placeholder="请选择内容风格" options={styleOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="tone"
                  label="写作语气"
                  rules={[{ required: true, message: '请选择写作语气' }]}
                >
                  <div ref={toneRef}>
                    <Select placeholder="请选择写作语气" options={toneOptions} />
                  </div>
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item>
                  <div ref={submitRef}>
                    <Button type="primary" htmlType="submit" loading={isGenerating} style={{ width: '100%' }}>
                      {isGenerating ? <Spin /> : '生成小红书文案'}
                    </Button>
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        {generatedContent && (
          <Card title="生成结果" extra={
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button icon={<CopyOutlined />} onClick={handleCopy}>复制</Button>
              <Button icon={<DownloadOutlined />} onClick={handleDownload}>下载</Button>
            </div>
          }>
            <div ref={resultRef} style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: 1.6 }}>
              {generatedContent}
            </div>
          </Card>
        )}
      </div>

      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </>
  );
}